package com.aruba.ioclib

import android.view.View
import com.aruba.ioclib.annotations.BindID
import com.aruba.ioclib.annotations.ContentView
import com.aruba.ioclib.annotations.Event
import com.aruba.ioclib.annotations.OnClick
import java.lang.ref.WeakReference
import java.lang.reflect.Proxy
import java.util.*

/**
 * 注入工具
 * Created by aruba on 2021/10/27.
 */
object InjectUtils {

    fun inject(activity: BaseActivity) {
        injectContentView(activity)
        injectViewId(activity)
        injectClick(activity, OnClick::class.java) {
            it.ids
        }
    }

    /**
     * 注入布局文件
     */
    private fun injectContentView(activity: BaseActivity) {
        activity.javaClass.getAnnotation(ContentView::class.java)?.apply {
            activity.setContentView(value)
        }
    }

    /**
     * 注入控件id
     */
    private fun injectViewId(activity: BaseActivity) {
        activity.javaClass.declaredFields.filter { field ->
            field.getAnnotation(BindID::class.java) != null
        }.forEach { field ->
            field.apply {
                isAccessible = true
                set(activity, activity.findViewById(getAnnotation(BindID::class.java)!!.id))
            }
        }
    }

    /**
     * 注入点击事件
     */
    private inline fun <T : Annotation> injectClick(
        activity: BaseActivity,
        clz: Class<out T>,
        getIds: (annotation: T) -> IntArray
    ) {
        //获取方法
        activity.javaClass.declaredMethods.filter { method ->
            //过滤非OnClick注解
            method.getAnnotation(clz) != null
        }.forEach { method -> //method 为 Activity中的clickView方法
            //获取OnClick注解
            val onClick = method.getAnnotation(clz)
            //获取控件id数组
            val ids = getIds(onClick)

            //获取OnClick注解的 元注解：Event
            method.annotations.forEach {
                //强转成Java Annotation对象,因为kotlin无法获取元注解（注解的注解）
                (it as java.lang.annotation.Annotation).annotationType()
                    .getAnnotation(Event::class.java)
                    ?.apply {
                        //给每个View绑定事件
                        ids.forEach { id ->
                            val view: View = activity.findViewById(id)
                            //获取setOnClickListener方法，入参为View.OnClickListener
                            val setOnClickListenerMethod =
                                view.javaClass.getMethod(setter, listenerClz.java)

                            //绑定 点击事件回调函数名onClick 与 Activity中的clickView方法（被OnClick注解的方法） 的关系
                            val map = mapOf(listenerCallbackMethodName to method)

                            //动态代理
                            val handler = ClickInvocationHandler(WeakReference(activity), map)
                            //动态代理生成的对象：点击事件匿名内部类
                            val proxy = Proxy.newProxyInstance(
                                listenerClz.java.classLoader,
                                arrayOf(listenerClz.java),
                                handler
                            )

                            //为view设置setOnClickListener
                            setOnClickListenerMethod.invoke(view, proxy)
                        }
                    }
            }
        }
    }

}